import { Button, Checkbox, Container, Group, Pagination, Table, Modal, Text, TextInput, NumberInput } from "@mantine/core";
import { useEffect, useState } from "react";
import axios from "axios";
import { notifications } from '@mantine/notifications';
import { modals } from '@mantine/modals';

interface Camera {
    id: number;
    url: string;
    camera_name: string;
    camera_brand: string;
    camera_price: number;
    sensor_type: string;
    effective_pixels: number;
    max_resolution: string;
    focus_mode: string;
    screen_size: string;
}

function CameraPage() {
    const [selectedRows, setSelectedRows] = useState<number[]>([]);
    const [cameraList, setCameraList] = useState<Camera[]>([]);
    const [pageInfo, setPageInfo] = useState<any>();
    const [detailsModalOpen, setDetailsModalOpen] = useState(false);
    const [currentCamera, setCurrentCamera] = useState<any>(null);
    const [editModalOpen, setEditModalOpen] = useState(false);
    const [editingCamera, setEditingCamera] = useState<any>(null);
    const [createModalOpen, setCreateModalOpen] = useState(false);
    const [newCamera, setNewCamera] = useState<any>({
        camera_name: '',
        camera_brand: '',
        camera_price: 0,
        sensor_type: '',
        sensor_size: '',
        effective_pixels: 0,
        max_resolution: '',
        video_resolution: '',
        focus_mode: '',
        focus_points: 0,
        max_aperture: '',
        screen_size: '',
        screen_type: '',
        exposure_mode: '',
        exposure_compensation: '',
        metering_mode: '',
        continuous_shooting: '',
        shutter_delay: '',
        white_balance: '',
        iso_range: '',
        shutter_speed: '',
        shooting_mode: '',
        storage_type: '',
        file_format: '',
        image_format: '',
        raw_support: false
    });

    const [adminFlag, setAdminFlag] = useState('')

    useEffect(() => {
        getCameraInfo({ page: 1, per_page: 10 })
        // const adminFlag = localStorage.getItem('user') as string
        setAdminFlag(localStorage.getItem('user_role') as string)
        // console.log(adminFlag)

    }, [])

    const getCameraInfo = (condition: any) => {
        axios.get("/app-api/get-cameras", { params: condition }).then((res) => {
            setCameraList(res.data.cameras)
            setPageInfo(res.data.pagination)
        })
    }

    const handleViewDetails = (camera: any) => {
        setCurrentCamera(camera);
        setDetailsModalOpen(true);
    };

    const handleEdit = (camera: any) => {
        setEditingCamera({
            id: camera.id,
            camera_name: camera.camera_name,
            camera_brand: camera.camera_brand,
            camera_price: camera.camera_price,
            sensor_type: camera.sensor_type,
            effective_pixels: camera.effective_pixels,
            max_resolution: camera.max_resolution,
            focus_mode: camera.focus_mode,
            screen_size: camera.screen_size
        });
        setEditModalOpen(true);
    };

    const handleSaveEdit = () => {
        axios.put(`/app-api/update-camera/${editingCamera.id}`, editingCamera)
            .then(() => {
                setCameraList(cameraList.map((camera: any) =>
                    camera.id === editingCamera.id ? editingCamera : camera
                ));
                setEditModalOpen(false);
                notifications.show({
                    title: '修改成功',
                    message: '记录已成功更新',
                    color: 'green',
                });
            })
            .catch((error) => {
                notifications.show({
                    title: '修改失败',
                    message: '更新记录时发生错误',
                    color: 'red',
                });
            });
    };

    const handleDelete = (cameraId: number) => {
        modals.openConfirmModal({
            title: '确认删除',
            centered: true,
            children: (
                <Text size="sm">
                    您确定要删除这条记录吗？此操作不可撤销。
                </Text>
            ),
            labels: { confirm: '确认删除', cancel: '取消' },
            confirmProps: { color: 'red' },
            cancelProps: { color: 'gray' },
            onConfirm: () => {
                axios.delete(`/app-api/delete-camera/${cameraId}`).then(() => {
                    setCameraList(cameraList.filter((camera: any) => camera.id !== cameraId));
                    notifications.show({
                        title: '删除成功',
                        message: '记录已成功删除',
                        color: 'green',
                    });
                });
            },
        });
    };

    const rows = cameraList.map((element: any) => (
        <Table.Tr
            key={element.id}
            bg={selectedRows.includes(element.id) ? 'var(--mantine-color-blue-light)' : undefined}
        >
            <Table.Td>{element.camera_name}</Table.Td>
            <Table.Td>{element.camera_brand}</Table.Td>
            <Table.Td>{element.camera_price}</Table.Td>
            <Table.Td>{element.sensor_type}</Table.Td>
            <Table.Td>{element.effective_pixels}万</Table.Td>
            <Table.Td>{element.max_resolution}</Table.Td>
            <Table.Td>{element.focus_mode}</Table.Td>
            <Table.Td>{element.screen_size}</Table.Td>
            <Table.Td>
                <Group gap={4} className="w-full flex justify-center items-center">
                    <Button size={'xs'} color={'green'} onClick={() => handleViewDetails(element)}>详情</Button>
                    {(localStorage.getItem('user_role') as string) == '0' && (
                        <>
                            <Button size={'xs'} onClick={() => handleEdit(element)}>编辑</Button>
                            <Button size={'xs'} color={'red'} onClick={() => handleDelete(element.id)}>删除</Button>
                        </>
                    )}
                </Group>
            </Table.Td>
        </Table.Tr>
    ));

    const handleCreateCamera = () => {
        axios.post('/app-api/create-camera', newCamera)
            .then(() => {
                getCameraInfo({ page: 1, per_page: 10 });
                setCreateModalOpen(false);
                setNewCamera({
                    camera_name: '',
                    camera_brand: '',
                    camera_price: 0,
                    // ... reset other fields
                });
                notifications.show({
                    title: '创建成功',
                    message: '新相机信息已添加',
                    color: 'green',
                });
            })
            .catch((error) => {
                notifications.show({
                    title: '创建失败',
                    message: '添加相机信息时发生错误',
                    color: 'red',
                });
            });
    };

    return (
        <div className={'mx-[unset]'}>
            <div className={'py-[10px]'}>
                <Table.ScrollContainer minWidth={500}>
                </Table.ScrollContainer>
                <Table withTableBorder withColumnBorders stickyHeader>
                    <Table.Thead>
                        <Table.Tr>
                            <Table.Th align={'center'} className={"w-[200px]"}>
                                <div className={'w-full flex justify-center'}>名称</div>
                            </Table.Th>
                            <Table.Th align={'center'} className={'align-middle'}>品牌</Table.Th>
                            <Table.Th>价格</Table.Th>
                            <Table.Th>传感器类型</Table.Th>
                            <Table.Th>有效像素</Table.Th>
                            <Table.Th>最高分辨率</Table.Th>
                            <Table.Th>对焦方式</Table.Th>
                            <Table.Th>屏幕尺寸</Table.Th>
                            <Table.Th className={"w-[200px]"}>
                                <div className="w-full flex justify-center items-center">
                                    操作
                                </div>
                            </Table.Th>
                        </Table.Tr>
                    </Table.Thead>
                    <Table.Tbody>{rows}</Table.Tbody>
                </Table>
            </div>
            <div className={'py-[10px]'}>
                {
                    pageInfo && (
                        <Pagination total={pageInfo.pages as any} onPreviousPage={() => {
                            if (pageInfo.has_prev) {
                                getCameraInfo({ page: pageInfo.prev_num, per_page: pageInfo.per_page })
                            }
                        }} onNextPage={() => {
                            if (pageInfo.has_next) {
                                getCameraInfo({ page: pageInfo.next_num, per_page: pageInfo.per_page })
                            }
                        }} onChange={(page: number) => {
                            getCameraInfo({ page: page, per_page: pageInfo.per_page })
                        }} />
                    )
                }
            </div>
            <Modal
                opened={detailsModalOpen}
                onClose={() => setDetailsModalOpen(false)}
                title="相机详情"
                size="lg"
            >
                {currentCamera && (
                    <div className="space-y-4">
                        <Text><strong>名称：</strong>{currentCamera.camera_name}</Text>
                        <Text><strong>品牌：</strong>{currentCamera.camera_brand}</Text>
                        <Text><strong>价格：</strong>{currentCamera.camera_price}元</Text>
                        <Text><strong>传感器类型：</strong>{currentCamera.sensor_type}</Text>
                        <Text><strong>传感器尺寸：</strong>{currentCamera.sensor_size}</Text>
                        <Text><strong>有效像素：</strong>{currentCamera.effective_pixels}万</Text>
                        <Text><strong>最大分辨率：</strong>{currentCamera.max_resolution}</Text>
                        <Text><strong>视频分辨率：</strong>{currentCamera.video_resolution}</Text>
                        <Text><strong>对焦模式：</strong>{currentCamera.focus_mode}</Text>
                        <Text><strong>对焦点数：</strong>{currentCamera.focus_points}</Text>
                        <Text><strong>最大光圈：</strong>{currentCamera.max_aperture}</Text>
                        <Text><strong>屏幕尺寸：</strong>{currentCamera.screen_size}</Text>
                        <Text><strong>屏幕类型：</strong>{currentCamera.screen_type}</Text>
                        <Text><strong>曝光模式：</strong>{currentCamera.exposure_mode}</Text>
                        <Text><strong>曝光补偿：</strong>{currentCamera.exposure_compensation}</Text>
                        <Text><strong>测光模式：</strong>{currentCamera.metering_mode}</Text>
                        <Text><strong>连拍速度：</strong>{currentCamera.continuous_shooting}</Text>
                        <Text><strong>快门延迟：</strong>{currentCamera.shutter_delay}</Text>
                        <Text><strong>白平衡：</strong>{currentCamera.white_balance}</Text>
                        <Text><strong>ISO范围：</strong>{currentCamera.iso_range}</Text>
                        <Text><strong>快门速度：</strong>{currentCamera.shutter_speed}</Text>
                        <Text><strong>拍摄模式：</strong>{currentCamera.shooting_mode}</Text>
                        <Text><strong>存储类型：</strong>{currentCamera.storage_type}</Text>
                        <Text><strong>文件格式：</strong>{currentCamera.file_format}</Text>
                        <Text><strong>图像格式：</strong>{currentCamera.image_format}</Text>
                        <Text><strong>RAW支持：</strong>{currentCamera.raw_support ? '是' : '否'}</Text>
                    </div>
                )}
            </Modal>
            <Modal
                opened={editModalOpen}
                onClose={() => setEditModalOpen(false)}
                title="修改相机信息"
                size="lg"
            >
                {editingCamera && (
                    <div className="space-y-4">
                        <TextInput
                            label="名称"
                            value={editingCamera.camera_name}
                            onChange={(e) => setEditingCamera({
                                ...editingCamera,
                                camera_name: e.target.value
                            })}
                        />
                        <TextInput
                            label="品牌"
                            value={editingCamera.camera_brand}
                            onChange={(e) => setEditingCamera({
                                ...editingCamera,
                                camera_brand: e.target.value
                            })}
                        />
                        <NumberInput
                            label="价格"
                            value={editingCamera.camera_price}
                            onChange={(value) => setEditingCamera({
                                ...editingCamera,
                                camera_price: value
                            })}
                        />
                        <TextInput
                            label="传感器类型"
                            value={editingCamera.sensor_type}
                            onChange={(e) => setEditingCamera({
                                ...editingCamera,
                                sensor_type: e.target.value
                            })}
                        />
                        <TextInput
                            label="传感器尺寸"
                            value={editingCamera.sensor_size}
                            onChange={(e) => setEditingCamera({
                                ...editingCamera,
                                sensor_size: e.target.value
                            })}
                        />
                        <NumberInput
                            label="有效像素（万）"
                            value={editingCamera.effective_pixels}
                            onChange={(value) => setEditingCamera({
                                ...editingCamera,
                                effective_pixels: value
                            })}
                        />
                        <TextInput
                            label="最大分辨率"
                            value={editingCamera.max_resolution}
                            onChange={(e) => setEditingCamera({
                                ...editingCamera,
                                max_resolution: e.target.value
                            })}
                        />
                        <TextInput
                            label="视频分辨率"
                            value={editingCamera.video_resolution}
                            onChange={(e) => setEditingCamera({
                                ...editingCamera,
                                video_resolution: e.target.value
                            })}
                        />
                        <TextInput
                            label="对焦模式"
                            value={editingCamera.focus_mode}
                            onChange={(e) => setEditingCamera({
                                ...editingCamera,
                                focus_mode: e.target.value
                            })}
                        />
                        <NumberInput
                            label="对焦点数"
                            value={editingCamera.focus_points}
                            onChange={(value) => setEditingCamera({
                                ...editingCamera,
                                focus_points: value
                            })}
                        />
                        <TextInput
                            label="最大光圈"
                            value={editingCamera.max_aperture}
                            onChange={(e) => setEditingCamera({
                                ...editingCamera,
                                max_aperture: e.target.value
                            })}
                        />
                        <TextInput
                            label="屏幕尺寸"
                            value={editingCamera.screen_size}
                            onChange={(e) => setEditingCamera({
                                ...editingCamera,
                                screen_size: e.target.value
                            })}
                        />
                        <TextInput
                            label="屏幕类型"
                            value={editingCamera.screen_type}
                            onChange={(e) => setEditingCamera({
                                ...editingCamera,
                                screen_type: e.target.value
                            })}
                        />
                        <TextInput
                            label="曝光模式"
                            value={editingCamera.exposure_mode}
                            onChange={(e) => setEditingCamera({
                                ...editingCamera,
                                exposure_mode: e.target.value
                            })}
                        />
                        <TextInput
                            label="曝光补偿"
                            value={editingCamera.exposure_compensation}
                            onChange={(e) => setEditingCamera({
                                ...editingCamera,
                                exposure_compensation: e.target.value
                            })}
                        />
                        <TextInput
                            label="测光方式"
                            value={editingCamera.metering_mode}
                            onChange={(e) => setEditingCamera({
                                ...editingCamera,
                                metering_mode: e.target.value
                            })}
                        />
                        <TextInput
                            label="连拍速度"
                            value={editingCamera.continuous_shooting}
                            onChange={(e) => setEditingCamera({
                                ...editingCamera,
                                continuous_shooting: e.target.value
                            })}
                        />
                        <TextInput
                            label="快门延迟"
                            value={editingCamera.shutter_delay}
                            onChange={(e) => setEditingCamera({
                                ...editingCamera,
                                shutter_delay: e.target.value
                            })}
                        />
                        <TextInput
                            label="白平衡模式"
                            value={editingCamera.white_balance}
                            onChange={(e) => setEditingCamera({
                                ...editingCamera,
                                white_balance: e.target.value
                            })}
                        />
                        <TextInput
                            label="ISO范围"
                            value={editingCamera.iso_range}
                            onChange={(e) => setEditingCamera({
                                ...editingCamera,
                                iso_range: e.target.value
                            })}
                        />
                        <TextInput
                            label="快门速度"
                            value={editingCamera.shutter_speed}
                            onChange={(e) => setEditingCamera({
                                ...editingCamera,
                                shutter_speed: e.target.value
                            })}
                        />
                        <TextInput
                            label="拍摄模式"
                            value={editingCamera.shooting_mode}
                            onChange={(e) => setEditingCamera({
                                ...editingCamera,
                                shooting_mode: e.target.value
                            })}
                        />
                        <TextInput
                            label="存储卡类型"
                            value={editingCamera.storage_type}
                            onChange={(e) => setEditingCamera({
                                ...editingCamera,
                                storage_type: e.target.value
                            })}
                        />
                        <TextInput
                            label="文件格式"
                            value={editingCamera.file_format}
                            onChange={(e) => setEditingCamera({
                                ...editingCamera,
                                file_format: e.target.value
                            })}
                        />
                        <TextInput
                            label="图片格式"
                            value={editingCamera.image_format}
                            onChange={(e) => setEditingCamera({
                                ...editingCamera,
                                image_format: e.target.value
                            })}
                        />
                        <Checkbox
                            label="RAW格式支持"
                            checked={editingCamera.raw_support}
                            onChange={(e) => setEditingCamera({
                                ...editingCamera,
                                raw_support: e.currentTarget.checked
                            })}
                        />
                        <TextInput
                            label="最大支持容量"
                            value={editingCamera.max_capacity}
                            onChange={(e) => setEditingCamera({
                                ...editingCamera,
                                max_capacity: e.target.value
                            })}
                        />
                        <Group justify="flex-end" mt="md">
                            <Button variant="light" onClick={() => setEditModalOpen(false)}>取消</Button>
                            <Button onClick={handleSaveEdit}>保存</Button>
                        </Group>
                    </div>
                )}
            </Modal>
            <Modal opened={createModalOpen}
                onClose={() => setCreateModalOpen(false)}
                title="新建相机信息"
                size="lg"
            >
                <div className="space-y-4">
                    <TextInput
                        label="名称"
                        value={newCamera.camera_name}
                        onChange={(e) => setNewCamera({
                            ...newCamera,
                            camera_name: e.target.value
                        })}
                    />
                    <TextInput
                        label="品牌"
                        value={newCamera.camera_brand}
                        onChange={(e) => setNewCamera({
                            ...newCamera,
                            camera_brand: e.target.value
                        })}
                    />
                    <NumberInput
                        label="价格"
                        value={newCamera.camera_price}
                        onChange={(value) => setNewCamera({
                            ...newCamera,
                            camera_price: value
                        })}
                    />
                    <TextInput
                        label="传感器类型"
                        value={newCamera.sensor_type}
                        onChange={(e) => setNewCamera({
                            ...newCamera,
                            sensor_type: e.target.value
                        })}
                    />
                    <TextInput
                        label="传感器尺寸"
                        value={newCamera.sensor_size}
                        onChange={(e) => setNewCamera({
                            ...newCamera,
                            sensor_size: e.target.value
                        })}
                    />
                    <NumberInput
                        label="有效像素（万）"
                        value={newCamera.effective_pixels}
                        onChange={(value) => setNewCamera({
                            ...newCamera,
                            effective_pixels: value
                        })}
                    />
                    <TextInput
                        label="最大分辨率"
                        value={newCamera.max_resolution}
                        onChange={(e) => setNewCamera({
                            ...newCamera,
                            max_resolution: e.target.value
                        })}
                    />
                    <TextInput
                        label="视频分辨率"
                        value={newCamera.video_resolution}
                        onChange={(e) => setNewCamera({
                            ...newCamera,
                            video_resolution: e.target.value
                        })}
                    />
                    <TextInput
                        label="对焦模式"
                        value={newCamera.focus_mode}
                        onChange={(e) => setNewCamera({
                            ...newCamera,
                            focus_mode: e.target.value
                        })}
                    />
                    <NumberInput
                        label="对焦点数"
                        value={newCamera.focus_points}
                        onChange={(value) => setNewCamera({
                            ...newCamera,
                            focus_points: value
                        })}
                    />
                    <TextInput
                        label="最大光圈"
                        value={newCamera.max_aperture}
                        onChange={(e) => setNewCamera({
                            ...newCamera,
                            max_aperture: e.target.value
                        })}
                    />
                    <TextInput
                        label="屏幕尺寸"
                        value={newCamera.screen_size}
                        onChange={(e) => setNewCamera({
                            ...newCamera,
                            screen_size: e.target.value
                        })}
                    />
                    <TextInput
                        label="屏幕类型"
                        value={newCamera.screen_type}
                        onChange={(e) => setNewCamera({
                            ...newCamera,
                            screen_type: e.target.value
                        })}
                    />
                    <Group justify="flex-end" mt="md">
                        <Button variant="light" onClick={() => setCreateModalOpen(false)}>取消</Button>
                        <Button onClick={handleCreateCamera}>创建</Button>
                    </Group>
                </div>
            </Modal>
        </div>
    );
}

const CameraChatTable = (props: { cameras: Camera[] }) => {
    const { cameras } = props;
    const [detailsModalOpen, setDetailsModalOpen] = useState(false);
    const [currentCamera, setCurrentCamera] = useState<any>(null);

    const handleDetailsClick = (camera: any) => {
        setCurrentCamera(camera);
        setDetailsModalOpen(true);
    };

    return (
        <>
            <Modal
                opened={detailsModalOpen}
                onClose={() => setDetailsModalOpen(false)}
                title="相机详情"
                size="lg"
            >
                {currentCamera && (
                    <div className="space-y-4">
                        <Text><strong>名称：</strong>{currentCamera.camera_name}</Text>
                        <Text><strong>品牌：</strong>{currentCamera.camera_brand}</Text>
                        <Text><strong>价格：</strong>{currentCamera.camera_price}元</Text>
                        <Text><strong>传感器类型：</strong>{currentCamera.sensor_type}</Text>
                        <Text><strong>传感器尺寸：</strong>{currentCamera.sensor_size}</Text>
                        <Text><strong>有效像素：</strong>{currentCamera.effective_pixels}万</Text>
                        <Text><strong>最大分辨率：</strong>{currentCamera.max_resolution}</Text>
                        <Text><strong>视频分辨率：</strong>{currentCamera.video_resolution}</Text>
                        <Text><strong>对焦模式：</strong>{currentCamera.focus_mode}</Text>
                        <Text><strong>对焦点数：</strong>{currentCamera.focus_points}</Text>
                        <Text><strong>最大光圈：</strong>{currentCamera.max_aperture}</Text>
                        <Text><strong>屏幕尺寸：</strong>{currentCamera.screen_size}</Text>
                        <Text><strong>屏幕类型：</strong>{currentCamera.screen_type}</Text>
                        <Text><strong>曝光模式：</strong>{currentCamera.exposure_mode}</Text>
                        <Text><strong>曝光补偿：</strong>{currentCamera.exposure_compensation}</Text>
                        <Text><strong>测光模式：</strong>{currentCamera.metering_mode}</Text>
                        <Text><strong>连拍速度：</strong>{currentCamera.continuous_shooting}</Text>
                        <Text><strong>快门延迟：</strong>{currentCamera.shutter_delay}</Text>
                        <Text><strong>白平衡：</strong>{currentCamera.white_balance}</Text>
                        <Text><strong>ISO范围：</strong>{currentCamera.iso_range}</Text>
                        <Text><strong>快门速度：</strong>{currentCamera.shutter_speed}</Text>
                        <Text><strong>拍摄模式：</strong>{currentCamera.shooting_mode}</Text>
                        <Text><strong>存储类型：</strong>{currentCamera.storage_type}</Text>
                        <Text><strong>文件格式：</strong>{currentCamera.file_format}</Text>
                        <Text><strong>图像格式：</strong>{currentCamera.image_format}</Text>
                        <Text><strong>RAW支持：</strong>{currentCamera.raw_support ? '是' : '否'}</Text>
                    </div>
                )}
            </Modal>
            <Table verticalSpacing="xs" highlightOnHover striped withColumnBorders
                styles={{
                    thead: {
                        '& tr': {
                            backgroundColor: '#007bff',
                            color: 'white'
                        },
                        '& th': {
                            borderBottom: '2px solid #e0e0e0'
                        }
                    },
                    tbody: {
                        '& tr': {
                            '&:nth-of-type(even)': {
                                backgroundColor: '#f8f9fa'
                            },
                            '&:hover': {
                                backgroundColor: '#e9ecef'
                            }
                        }
                    },
                    td: {
                        border: '1px solid #f0f0f0'
                    }
                }}>
                <Table.Thead>
                    <Table.Tr>
                        <Table.Th>名称</Table.Th>
                        <Table.Th>品牌</Table.Th>
                        <Table.Th>传感器类型</Table.Th>
                        <Table.Th>价格</Table.Th>
                    </Table.Tr>
                </Table.Thead>
                <Table.Tbody>
                    {cameras.map((camera, index) => {
                        return (
                            <Table.Tr key={index}>
                                <Table.Td>{camera.camera_name}</Table.Td>
                                <Table.Td>{camera.camera_brand}</Table.Td>
                                <Table.Td>{camera.sensor_type}</Table.Td>
                                <Table.Td>{camera.camera_price}￥</Table.Td>
                                <Table.Td>
                                    <Group>
                                        <Button onClick={() => handleDetailsClick(camera)}>详情</Button>
                                        <Button color="green" onClick={() => { window.open(camera.url, '_blank') }}>网站</Button>
                                    </Group>
                                </Table.Td>
                            </Table.Tr>
                        )
                    })}
                </Table.Tbody>
            </Table>
        </>
    )

}

export { CameraPage, CameraChatTable };